import axios, { type AxiosResponse } from 'axios'
import { API_BASE_URL, API_ENDPOINTS, HTTP_STATUS } from '@/config/api'
import { authService } from './authService'
import router from '@/router'

// 创建axios实例
const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    // 自动添加认证token
    const token = authService.getToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response: AxiosResponse) => {
    return response
  },
  (error) => {
    if (error.response) {
      // 服务器返回错误状态码
      const { status, data } = error.response
      switch (status) {
        case HTTP_STATUS.BAD_REQUEST:
          console.error('请求参数错误:', data.error)
          break
        case HTTP_STATUS.UNAUTHORIZED:
          console.error('未授权访问')
          // 清除认证信息并跳转到登录页
          authService.logout()
          if (router.currentRoute.value.path !== '/login') {
            router.push('/login')
          }
          break
        case HTTP_STATUS.FORBIDDEN:
          console.error('禁止访问')
          break
        case HTTP_STATUS.NOT_FOUND:
          console.error('资源不存在')
          break
        case HTTP_STATUS.CONFLICT:
          console.error('资源冲突:', data.error)
          break
        case HTTP_STATUS.INTERNAL_SERVER_ERROR:
          console.error('服务器内部错误')
          break
        default:
          console.error('未知错误:', status, data)
      }
    } else if (error.request) {
      // 请求已发出但没有收到响应
      console.error('网络错误，请检查网络连接')
    } else {
      // 请求配置错误
      console.error('请求配置错误:', error.message)
    }
    return Promise.reject(error)
  }
)

// 通用API方法
export const apiService = {
  // GET请求
  get: <T>(url: string, params?: any): Promise<T> => {
    return api.get(url, { params }).then(response => response.data)
  },

  // POST请求
  post: <T>(url: string, data?: any): Promise<T> => {
    return api.post(url, data).then(response => response.data)
  },

  // PUT请求
  put: <T>(url: string, data?: any): Promise<T> => {
    return api.put(url, data).then(response => response.data)
  },

  // DELETE请求
  delete: <T>(url: string): Promise<T> => {
    return api.delete(url).then(response => response.data)
  },

  // 文件上传
  upload: <T>(url: string, formData: FormData): Promise<T> => {
    return api.post(url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }).then(response => response.data)
  }
}

export default api 